import React, { useState } from 'react';
import { Modal, Tree, Table, Input, Button, Radio, Tooltip, Checkbox, Select, message } from 'antd';
import { 
  SettingOutlined, 
  ReloadOutlined,
  PlusOutlined
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import './SelectProductModal.scss';
import AddProductModal from './AddProductModal';
import ColumnSettingModal, { ColumnConfig } from './ColumnSettingModal';

const { Search } = Input;
const { Option } = Select;

interface SelectProductModalProps {
  visible: boolean;
  onCancel: () => void;
  onOk: (selectedProducts: any[]) => void;
}

// 模拟商品分类数据
const treeData: DataNode[] = [
  {
    title: '全部分类',
    key: 'all',
    children: [
      {
        title: '劳务费',
        key: 'labor',
      },
      {
        title: '常用资料',
        key: 'common',
        children: [
          {
            title: '其他商品',
            key: 'others',
          }
        ]
      },
      {
        title: '库存直调',
        key: 'inventory',
      },
      {
        title: '快速添加',
        key: 'quickAdd',
      }
    ],
  },
];

// 模拟商品数据
const mockProducts = [
  {
    key: '1',
    name: '监控/电脑/打印机',
    image: '',
    auxiliaryAttr: '',
    productCode: '',
    specModel: '',
    unit: '无',
    purchasePrice: 0,
    category: '快速添加',
    salePrice: 21800,
    stock: 0
  },
  {
    key: '2',
    name: '惠普打印机180N粉盒',
    image: '',
    auxiliaryAttr: '',
    productCode: '',
    specModel: '',
    unit: '套',
    purchasePrice: 0,
    category: '快速添加',
    salePrice: 85,
    stock: 0
  },
  {
    key: '3',
    name: '电脑',
    image: '',
    auxiliaryAttr: '',
    productCode: '',
    specModel: '',
    unit: '无',
    purchasePrice: 0,
    category: '无',
    salePrice: 0,
    stock: 0
  },
  {
    key: '4',
    name: '特人特别',
    image: '',
    auxiliaryAttr: '',
    productCode: '',
    specModel: '',
    unit: '无',
    purchasePrice: 0,
    category: '快速添加',
    salePrice: 10,
    stock: 0
  },
  {
    key: '5',
    name: '金科系统/扫码枪',
    image: '',
    auxiliaryAttr: '',
    productCode: '',
    specModel: '',
    unit: '无',
    purchasePrice: 0,
    category: '快速添加',
    salePrice: 620,
    stock: 0
  }
];

const SelectProductModal: React.FC<SelectProductModalProps> = ({
  visible,
  onCancel,
  onOk
}) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [showMultiStock, setShowMultiStock] = useState(false);
  const [quantities, setQuantities] = useState<{ [key: string]: number }>({});
  const [isAddProductVisible, setIsAddProductVisible] = useState(false);
  const [isColumnSettingVisible, setIsColumnSettingVisible] = useState(false);
  const [columnConfigs, setColumnConfigs] = useState<ColumnConfig[]>([
    { key: 'actions', title: '操作', visible: true },
    { key: 'image', title: '图片', visible: true },
    { key: 'name', title: '商品信息', visible: true },
    { key: 'specModel', title: '规格型号', visible: true },
    { key: 'barcode', title: '条码编号', visible: true },
    { key: 'unit', title: '单位', visible: true },
    { key: 'currentStock', title: '当前库存', visible: true },
    { key: 'quantity', title: '数量', visible: true },
    { key: 'price', title: '单价（元）', visible: true },
    { key: 'amount', title: '金额（元）', visible: true },
    { key: 'remark', title: '备注信息', visible: true },
  ]);

  const handleQuantityChange = (key: string, value: number) => {
    setQuantities({
      ...quantities,
      [key]: value
    });
  };

  const handleOk = () => {
    const selectedProducts = mockProducts
      .filter(product => selectedRowKeys.includes(product.key))
      .map(product => ({
        ...product,
        quantity: quantities[product.key] || 0
      }));
    onOk(selectedProducts);
  };

  const handleAddProductClick = () => {
    setIsAddProductVisible(true);
  };

  const handleAddProductCancel = () => {
    setIsAddProductVisible(false);
  };

  const handleAddProductOk = (productData: any) => {
    const newProduct = {
      id: String(Date.now()),
      key: String(Date.now()),
      name: productData.productName,
      specModel: productData.specModel,
      barcode: productData.barcode,
      unit: productData.unit,
      stock: 0,
      salePrice: Number(productData.wholesalePrice) || 0,
      quantity: 1
    };

    setSelectedRowKeys([...selectedRowKeys, newProduct.key]);
    setQuantities({
      ...quantities,
      [newProduct.key]: 1
    });
    setIsAddProductVisible(false);
    message.success('商品添加成功');
  };

  const showColumnSetting = () => {
    setIsColumnSettingVisible(true);
  };

  const handleColumnSettingCancel = () => {
    setIsColumnSettingVisible(false);
  };

  const handleColumnSettingOk = (newColumnConfigs: ColumnConfig[]) => {
    setColumnConfigs(newColumnConfigs);
    setIsColumnSettingVisible(false);
  };

  const columns = [
    {
      title: (
        <div className="checkbox-header">
          <Checkbox />
          <span>数量</span>
        </div>
      ),
      key: 'quantity',
      width: 80,
      render: (_: any, record: any) => (
        <Input 
          style={{ width: 60 }} 
          value={quantities[record.key] || ''}
          onChange={(e) => handleQuantityChange(record.key, Number(e.target.value))}
        />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      sorter: true,
      render: (text: string) => (
        <a href="#" className="product-name">{text}</a>
      ),
    },
    {
      title: '商品图像',
      dataIndex: 'image',
      key: 'image',
      width: 60,
      render: () => (
        <div className="image-placeholder" />
      ),
    },
    {
      title: '辅助属性',
      dataIndex: 'auxiliaryAttr',
      key: 'auxiliaryAttr',
      width: 100,
    },
    {
      title: '商品编号',
      dataIndex: 'productCode',
      key: 'productCode',
      sorter: true,
    },
    {
      title: '规格型号1',
      dataIndex: 'specModel',
      key: 'specModel',
      sorter: true,
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
      width: 80,
    },
    {
      title: '进货价格',
      dataIndex: 'purchasePrice',
      key: 'purchasePrice',
      width: 100,
    },
    {
      title: '商品分类',
      dataIndex: 'category',
      key: 'category',
      sorter: true,
    },
    {
      title: '销售价格',
      dataIndex: 'salePrice',
      key: 'salePrice',
      width: 100,
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  const getProductSelectionColumns = (columns: any[], configs: ColumnConfig[]) => {
    const visibleColumnKeys = configs
      .filter(config => config.visible)
      .map(config => config.key);
      
    return columns.filter(col => visibleColumnKeys.includes(col.key));
  };

  return (
    <>
      <Modal
        title="选择商品"
        open={visible}
        onCancel={onCancel}
        width={1200}
        style={{ top: 20 }}
        footer={[
          <Button key="cancel" onClick={onCancel}>
            取消
          </Button>,
          <Button key="ok" type="primary" onClick={handleOk}>
            选中
          </Button>,
        ]}
        className="select-product-modal"
      >
        <div className="modal-content">
          <div className="left-section">
            <div className="category-header">
              商品分类
            </div>
            <Tree
              treeData={treeData}
              defaultExpandAll
              defaultSelectedKeys={['all']}
            />
          </div>
          <div className="right-section">
            <div className="toolbar">
              <div className="left-tools">
                <Button type="primary">直接显示</Button>
                <Button>显示多仓库存</Button>
                <Tooltip title="设置">
                  <Button icon={<SettingOutlined />} onClick={showColumnSetting} />
                </Tooltip>
                <Button 
                  icon={<PlusOutlined />} 
                  onClick={handleAddProductClick}
                >
                  添加商品
                </Button>
                <Button icon={<ReloadOutlined />}>刷新</Button>
              </div>
              <div className="right-tools">
                <Search
                  placeholder="搜索商品、名称、规格、条码、属性、备注"
                  style={{ width: 300 }}
                  allowClear
                />
                <Button type="primary">查询</Button>
                <Button>高级搜索</Button>
              </div>
            </div>
            <Table
              rowSelection={rowSelection}
              columns={getProductSelectionColumns(columns, columnConfigs)}
              dataSource={mockProducts}
              size="small"
              scroll={{ y: 360 }}
              pagination={{
                total: mockProducts.length,
                pageSize: 30,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条`,
                current: 1,
                pageSizeOptions: ['30', '50', '100'],
              }}
            />
            <div className="table-footer">
              <div className="page-info">
                <span>1</span>
                <span>页</span>
                <span>确定</span>
                <span>共 309 条</span>
                <Select defaultValue="30" style={{ width: 100 }}>
                  <Option value="30">30 条/页</Option>
                  <Option value="50">50 条/页</Option>
                  <Option value="100">100 条/页</Option>
                </Select>
              </div>
            </div>
          </div>
        </div>
      </Modal>
      
      <AddProductModal
        visible={isAddProductVisible}
        onCancel={handleAddProductCancel}
        onOk={handleAddProductOk}
      />

      <ColumnSettingModal
        visible={isColumnSettingVisible}
        onCancel={handleColumnSettingCancel}
        onOk={handleColumnSettingOk}
        columnConfigs={columnConfigs}
      />
    </>
  );
};

export default SelectProductModal; 